<template>
  <div>
    <v-btn color="primary" @click="dialog = true" prepend-icon="mdi-upload">上传文件</v-btn>

    <v-dialog v-model="dialog" max-width="600px">
      <v-card>
        <v-card-title> 上传文件 </v-card-title>

        <v-card-text>
          <v-form ref="formRef" @submit.prevent="submitFile">
            <v-file-input
              label="选择文件"
              v-model="form.file"
              accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf"
              required
            ></v-file-input>

            <v-select
              v-model="form.tags"
              :items="tagOptions"
              label="选择标签"
              multiple
              item-title="name"
              item-value="id"
              chips
              clearable
            ></v-select>
          </v-form>
        </v-card-text>

        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="primary" @click="submitFile">提交</v-btn>
          <v-btn @click="dialog = false">取消</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'

import { getTags } from '@/api/tags'
import { uploadFile } from '@/api/files'
import { useMessageStore } from '@/stores/MessageStore.js'

const dialog = ref(false)
const formRef = ref(null)

const form = ref({
  file: null,
  name: '',
  type: '',
  tags: [],
})

const tagOptions = ref([]) // 下拉选项

// 获取可选标签（从后端）
onMounted(async () => {
  const res = await getTags() // 根据你的实际接口调整
  tagOptions.value = res.data
})

// 提交表单
const submitFile = async () => {
  if (!formRef.value.validate()) return

  const formData = new FormData()
  formData.append('file', form.value.file)
  form.value.tags.forEach((tagId) => {
    formData.append('tagIds', tagId)
  })

  try {
    dialog.value = false
    await uploadFile(formData)
  } catch (err) {
    console.error('上传失败', err)
    useMessageStore().trigger('上传失败', 'error')
  }
}
</script>
